package com.spark.actions.sys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.SqlSession;

import com.spark.core.Message;
import com.spark.core.SparkContext;
import com.spark.dao.SessionFactory;

public class RoleAction extends DefaultAction {
	public static final String FIELD_ROLE_MENU_ID = "ROLE_MENU_ID";
	public static final String FIELD_ROLE_ID = "ROLE_ID";
	public static final String FIELD_ROLE_NAME = "ROLE_NAME";
	public static final String FIELD_ROLE_MENUS = "ROLE_MENUS";
	public static final String FIELD_ROLE_USERS = "ROLE_USERS";
	public static final String FIELD_ROLE_USERS_REMOVE = "ROLE_USERS_REMOVE";
	
	public static final String FIELD_MENU_CHECKED = "CHECKED";
	
	/**
	 * 创建系统角色
	 * @param context
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void createRole(SparkContext context) throws Exception {
		doExecute(context, "sys_role.insert", ACTION_INSERT);
	}
	
	/**
	 * 更新系统角色.
	 * @param context
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void updateRole(SparkContext context) throws Exception {
		doExecute(context, "sys_role.update", ACTION_UPDATE);
	}
	
	@SuppressWarnings("unchecked")
	private boolean validateRole(Map map, Message message){
		return isNotEmpty(map.get(FIELD_ROLE_NAME), message,"角色名不能为空!");
	}
	
	@SuppressWarnings("unchecked")
	protected void doExecute(SparkContext context, String statement, String action) throws Exception{
		Map requestData = getRequestData(context);
		List list = (List)requestData.get(PARAMETER);
		Message message = new Message(true);
		if(list!=null && list.size() > 0){
			Map map = (Map)list.get(0);
			if(validateRole(map,message)){
				SqlSession sqlSession = SessionFactory.getSession(false);
				try {
					setCompanyId(map, context);
					Integer count = (Integer)sqlSession.selectOne("sys_role.selectDuplicateRole", map);
					if(count>0){
						message.setWarning("角色\""+map.get(FIELD_ROLE_NAME)+"\"已经存在!");
						message.setWidth(300);
						message.setHeiht(150);
					}else{
						doAction(sqlSession, action, statement,map);
						Integer roleId = (Integer)map.get(FIELD_ROLE_ID);
						List menuList = (List)map.get(FIELD_ROLE_MENUS);
						if(menuList!=null){
							Iterator it = menuList.iterator();
							List addList = new ArrayList();
							while(it.hasNext()){
								Map menu = (Map)it.next();
								Integer roleMenuId = (Integer)menu.get(FIELD_ROLE_MENU_ID);
								String checked = (String)menu.get(FIELD_MENU_CHECKED);
								if("Y".equals(checked) && roleMenuId == null){
									menu.put(FIELD_ROLE_ID, roleId);
									setCompanyId(menu,context);
									addList.add(menu);
								}else if("N".equals(checked) && roleMenuId != null){
									//菜单删除
									doAction(sqlSession, ACTION_DELETE, "sys_role_menu.delete", menu);									
								}
							}
							//菜单新增
							if(addList.size() >0){
								Map menuMap = new HashMap();
								menuMap.put("menus", addList);
								sqlSession.insert("sys_role_menu.batchInsert",menuMap);
							}
						}
						
						//成员列表删除
						List removeList = (List)map.get(FIELD_ROLE_USERS_REMOVE);
						if(removeList!=null){
							Iterator it = removeList.iterator();
							while(it.hasNext()){
								Map user = (Map)it.next();
								doAction(sqlSession, ACTION_DELETE, "sys_user_role.delete", user);	
							}
						}
						
						//成员列表新增
						List userList = (List)map.get(FIELD_ROLE_USERS);
						if(userList!=null){
							List addList = new ArrayList();
							Iterator it = userList.iterator();
							while(it.hasNext()){
								Map user = (Map)it.next();
								user.put(FIELD_ROLE_ID, roleId);
								setCompanyId(user,context);
								addList.add(user);
							}
							if(addList.size() >0){
								Map userMap = new HashMap();
								userMap.put("items", addList);
								sqlSession.insert("sys_user_role.batchInsert",userMap);
							}
						}
					}
					sqlSession.commit();
				} finally {
					SessionFactory.closeSession(sqlSession);
				}
			}
		}
		writeMessage(context, message);
	}
	
	
	/**
	 * 查询角色的菜单项
	 * @param context
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public void selectRoleAssignMenus(SparkContext context) throws ServletException, IOException {
		Map<String, Object> model = context.getModel();
		SqlSession sqlSession = SessionFactory.getSession();
		try {
			List menus = (List) sqlSession.selectList("sys_menu.selectMenus");
			HttpServletRequest request = context.getRequest();
			String roleId = request.getParameter(FIELD_ROLE_ID);
			List roleMenus = (List) sqlSession.selectList("sys_role_menu.selectRoleAssignMenus", roleId);
			if(roleMenus!=null && menus != null){
				Iterator rit = roleMenus.iterator();
				while(rit.hasNext()){
					Map roleMenu = (Map)rit.next();
					Integer roleMenuId = (Integer)roleMenu.get(MenuAction.FIELD_MENU_ID);
					Integer roleMenuPK = (Integer)roleMenu.get(FIELD_ROLE_MENU_ID);
					Iterator mit = menus.iterator();
					while(mit.hasNext()){
						Map menu = (Map)mit.next();
						Integer menuId = (Integer)menu.get(MenuAction.FIELD_MENU_ID);
						if(roleMenuId == menuId){
							menu.put(FIELD_ROLE_MENU_ID, roleMenuPK);
							menu.put(FIELD_MENU_CHECKED, "Y");
							break;
						}
					}
				}
			}
			model.put("sys_menus", menus);
		} finally {
			SessionFactory.closeSession(sqlSession);
		}
	}
	
	
}
